from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from apps.sms.services import SMSService  # 改为从sms应用导入服务
from apps.accounts.models import User  # 假设需要操作用户模型

class ChangePhoneView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        """请求更换手机号（触发短信发送）"""
        new_phone = request.data.get('phone')
        
        # 调用通用短信服务
        if not SMSService.send_code(request, new_phone, 'change_phone'):
            return Response({"error": "短信发送失败"}, status=400)
        
        return Response({"message": "验证码已发送"})

class ConfirmPhoneChangeView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        """确认更换手机号（验证短信）"""
        new_phone = request.data.get('phone')
        code = request.data.get('code')
        
        # 验证验证码
        if not SMSService.verify_code(request, new_phone, code, 'change_phone'):
            return Response({"error": "验证码无效或已过期"}, status=400)
        
        # 更新用户手机号
        user = request.user
        user.phone = new_phone
        user.save()
        
        return Response({"message": "手机号更换成功"})